<template>
  <div>
    <div class="search">
      <input v-model="kw" type="text" placeholder="请输入城市名称或拼音" />
    </div>
    <div class="search-content" ref="search" v-show="kwEmpty">
      <ul>
        <li v-for="item of list" :key="item.id" class="border-bottom-1px" @click="hdSearchClick(item.name)">
          {{ item.name }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import { mapMutations } from 'vuex'

export default {
  name: 'Search',

  props: ['cities'],

  computed: {
    kwEmpty() {
      return this.kw
    },
  },

  watch: {
    kw() {
      if (this.timer) {
        clearTimeout(this.timer)
      }

      if (!this.kw) {
        this.list = []
        return
      }

      this.timer = setTimeout(() => {
        let result = []
        for (let i in this.cities) {
          this.cities[i].forEach((item) => {
            if (item.spell.indexOf(this.kw) > -1 || item.name.indexOf(this.kw) > -1) {
              result.push(item)
            }
          })
        }
        this.list = result
      }, 150)
    },
  },

  methods: {
    hdSearchClick(city) {
      this.changeCity(city)
      this.$router.push('/')
    },

    ...mapMutations(['changeCity']),
  },

  data() {
    return {
      kw: '',
      list: [],
    }
  },

  mounted() {
    this.scroll = new BScroll(this.$refs.search, {
      probeType: 3,
      preventDefault: false,
      stopPropagation: true,
      observeDOM: true,
    })
  },
}
</script>

<style lang="scss" scoped>
.search {
  background: $bg;
  height: 0.72rem;
  display: flex;
  justify-content: center;
  position: relative;
  z-index: 99;
  input {
    outline: none;
    border: 0 none;
    line-height: 0.56rem;
    height: 0.56rem;
    width: 96%;
    box-sizing: border-box;
    padding: 0.05rem 0.1rem;
    border-radius: 0.1rem;
    text-align: center;
  }
}
.search-content {
  z-index: 1;
  position: fixed;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  height: calc(100vh - 1.58rem);
  background: #eee;
  li {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    color: #666;
    background: #fff;
    text-align: left;
  }
}
</style>
